package com.ruix.app.mapper;

import com.ruix.app.cache.CacheFactory;
import com.ruix.app.manager.UserManager;
import com.ruix.app.model.ClassDetail;
import com.ruix.app.model.ClassOwner;
import com.ruix.app.model.User;
import com.ruix.app.util.LogUitl;

import org.json.JSONObject;

/**
 * Created by hadexs on 2017/5/1.
 */

public class ClasssDetailMapper implements ApiMapper<ClassDetail> {


    private String classId;

    public ClasssDetailMapper(String classId) {
        this.classId = classId;
    }

    @Override
    public ClassDetail transform(JSONObject response) {
        ClassDetail detail = null;
        if (response != null) {
            JSONObject data = response.optJSONObject("data");
            if (data != null) {
                //// TODO: 2017/5/1
                String myRole = data.optString("my_role", "");
                String shareUrl = data.optString("share_url", "");
                UserManager.getCurrentUser().setRole(myRole);
                UserManager.sharedInstance().saveCurrentUser();
                boolean prohibited = data.optInt("prohibited", 0) == 1;
                UserManager.getCurrentUser().setProhibited(prohibited);
                JSONObject object = data.optJSONObject("class_info");
                if (object != null) {//
                    detail = new ClassDetail().parse(object);
                    detail.setProhibited(prohibited);
                    detail.setShareUrl(shareUrl);
                    detail.setClassId(classId);
                    detail.setRole(myRole);
                    CacheFactory.cacheClassDetail(detail);
                }
                JSONObject owner = data.optJSONObject("owner");
                if (owner != null && detail != null) {
                    detail.setClassOwnerName(owner.optString("name",""));
                }

                if (detail != null){
                    detail.setFirstOpenCircle(data.optInt("is_first",0)==1); //是否为第一次打开
                }
            }
        }
        return detail;
    }
}
